package com.hnevc.blogsystemdb;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	public Connection getConnection() throws ClassNotFoundException, SQLException  {
		String driver = Config.getValue("driver");
		String url = Config.getValue("url");
		String username = Config.getValue("username");
		String password = Config.getValue("password");
		
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,username,password);
			return conn;
		} catch (Exception e) {
			throw new SQLException("驱动错误或链接");
		}	
	}
	
	public void closeAll() throws SQLException{
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				throw new SQLException("无法关闭RS");
			}
		}
		if(pstmt != null){
			try {
				pstmt.close();
			} catch (SQLException e) {
				throw new SQLException("无法关闭pstmt");
			}
		}
		if(conn != null){
			try {
				rs.close();
			} catch (SQLException e) {
				throw new SQLException("无法关闭conn");
			}
		}
	}

	public ResultSet executeQuery(String preparedSql, String[] params) throws SQLException{
		try {
			
			pstmt = conn.prepareStatement(preparedSql);
			
			if(params!=null){
				for(int i=0;i<params.length;i++){
					pstmt.setString(i+1, params[i]);
				}
			}
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			throw new SQLException("SQL 执行错误"+preparedSql);
		}
		return rs;
		
	}

	public int executeUpdate(String preparedSql, String[] params) throws SQLException{
		
		int num = 0;
		try{
			System.out.println(conn.getAutoCommit());
			pstmt = conn.prepareStatement(preparedSql);
			if(params != null){
				for(int i=0;i<params.length;i++){
					pstmt.setString(i+1, params[i]);
				}
			}
			num = pstmt.executeUpdate();
		}catch(SQLException e){
			throw new SQLException("SQL 执行错误"+preparedSql);
		}
		return num;
	}
}	
